const path = require('path')

const glob = require('glob')
const {HotModuleReplacementPlugin} = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCSSExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')

// 生成多页面的配置
const setMPA = () => {
  const entry = {}
  const htmlWebpackPlugins = []

  const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'))
  entryFiles.forEach((entryFile) => {
    const match = entryFile.match(/\/src\/(.*)\/index.js/)
    const pageName = match && match[1]
    const template = entryFile.replace(/index.js$/, 'index.html')

    entry[pageName] = entryFile
    htmlWebpackPlugins.push(new HtmlWebpackPlugin({
      template,
      filename: `${pageName}.html`,
      chunk: ['index'],
      inject: true,
      minify: {
        html5: true,
        collapseWhitespace: true,
        preserveLineBreaks: false,
        minifyCSS: true,
        minifyJS: true,
        removeComments: false
      }
    }))
  })

  return {
    entry,
    htmlWebpackPlugins
  }
}

const {entry, htmlWebpackPlugins} = setMPA()

module.exports = {
  entry,
  output: {
    filename: '[name]_[hash:8].js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins: [
    new CleanWebpackPlugin(),
    new MiniCSSExtractPlugin(),
    new OptimizeCSSAssetsWebpackPlugin({
      assetNameRegExp: /\.css$/g,
      cssProcessor: require('cssnano')
    }),
  ].concat(htmlWebpackPlugins)
}
